package com.example.zhunongzonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhunongzonghe.common.Result;
import com.example.zhunongzonghe.dao.ZnUsersMapper;
import com.example.zhunongzonghe.entity.ZnUsers;
import com.example.zhunongzonghe.security.entity.LoginUser;
import com.example.zhunongzonghe.service.IZnUsersService;
import com.example.zhunongzonghe.utils.JwtUtils;
import com.example.zhunongzonghe.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;



@Service
public class ZnUsersServiceImpl extends ServiceImpl<ZnUsersMapper, ZnUsers> implements IZnUsersService {
    @Autowired
    private ZnUsersMapper znUsersMapper;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 通过用户名查询用户信息
     * @param userName
     * @return
     */
    @Override
    public ZnUsers getUserName(String userName) {
        LambdaQueryWrapper<ZnUsers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnUsers::getUserName,userName);
        ZnUsers users = this.getOne(queryWrapper);
        return users;
    }

    /**
     * 用户登录
     *
     * @param znUsers
     * @return
     */
    @Override
    public Map<String, Object> login(ZnUsers znUsers) {
        //用户在登录页面输入的用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(znUsers.getUserName(),znUsers.getPassword());
        //获取AuthenticationManager的authenticate方法来进行用户认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //判断上面那行的authenticate是否为null，如果是则认证没通过，就抛出异常
        if (Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过，就使用userid生成一个jwt，然后把jwt存入ResponseResult后返回
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userid = loginUser.getZnUsers().getId().toString();
        String jwt = jwtUtils.createJWT(userid);

        //把完整的用户信息存入redis，其中userid作为key，存入redis的时候加了前缀 login:
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        redisCache.setCacheObject("login:"+userid,loginUser);
        return map;
    }

    @Override
    public Result logout() {
        //获取我们在JwtAuthenticationTokenFilter类写的SecurityContextHolder对象中的用户id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //loginUser是我们在entity目录写好的实体类
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取用户id
        Long userid = loginUser.getZnUsers().getId().longValue();

        //根据用户id，删除redis中key
        redisCache.deleteObject("login:"+userid);
        return new Result(true,"注销成功",200);
    }


}
